package com.msb.mall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.mall.common.utils.PageUtils;
import com.msb.mall.common.utils.Query;

import com.msb.mall.product.dao.CategoryDao;
import com.msb.mall.product.entity.CategoryEntity;
import com.msb.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    /**
     * 逻辑批量删除操作
     * @param ids
     */
    @Override
    public void removeCategoryByIds(List<Long> ids) {
        // TODO 1.检查当前删除的菜单是否被其他地方引用，如果被引用则不允许删除

        // 2.批量删除
        baseMapper.deleteBatchIds(ids);
    }

    /**
     * 查询所有类别的数据，然后将数据转换成树形结构
     */
    @Override
    public List<CategoryEntity> queryPageWithTree() {
        // 查询所有类别数据
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 将商品分类信息拆解为树形结构
        return categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(categoryEntity -> categoryEntity.setChildren(getCategoryChildren(categoryEntity,categoryEntities))).sorted(this::setCategorySort)
                .collect(Collectors.toList());
    }



    /**
     * 查找该大类下的所有的小类  递归查找
     * @param categoryEntity  某个大类
     * @param categoryEntities 所有大类
     */
    private List<CategoryEntity> getCategoryChildren(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntities) {
        return categoryEntities.stream().filter(categoryEntity1 -> {
                    // 查询该大类下的所有小类
                    return categoryEntity.getCatId().equals(categoryEntity1.getParentCid());
                })
                .peek(entity -> entity.setChildren(getCategoryChildren(entity, categoryEntities)))
                .sorted(this::setCategorySort).collect(Collectors.toList());

    }

    private int setCategorySort(CategoryEntity entity1, CategoryEntity entity2) {
        return (entity1.getSort() == null ? 0 :entity1.getSort()) - (entity2.getSort() == null ? 0 : entity2.getSort());
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

}